﻿using System;
using System.IO;
using System.Reactive.Linq;
using System.Windows.Forms;

namespace Demo
{
	public partial class EventsIntoObservablesForm : Form
	{

		public EventsIntoObservablesForm()
		{
			InitializeComponent();
			GetMouseMoves();
			SetupFileWatcher();
		}

		private void Form3_Load(object sender, EventArgs e)
		{
			var res = from evt in Observable.FromEventPattern(textBox1, "TextChanged") 
			          select ((TextBox) evt.Sender).Text;
			res.Subscribe(s => textBox2.Text = s);
		}

		private void GetMouseMoves()
		{
			var mse = from evt in Observable.FromEventPattern<MouseEventArgs>(this, "MouseMove")
			          where evt.EventArgs.X == evt.EventArgs.Y select evt.EventArgs.X ;
			mse.Subscribe(args => mouseTxt.Text = args.ToString());
		}

		public void SetupFileWatcher()
		{
			var _fileSystemWatcher = new FileSystemWatcher
		        {
		        Path = @"C:\temp",
		        IncludeSubdirectories = false,
		        EnableRaisingEvents = true
		        };

			var fileDel = (from del in
			              	Observable.FromEventPattern<FileSystemEventHandler, FileSystemEventArgs>(
			              		h => _fileSystemWatcher.Deleted += h,
			              		h => _fileSystemWatcher.Deleted -= h)
						  where del.EventArgs.Name.Contains("brad")
						  select del);
			fileDel.ObserveOn(this).Subscribe(
				ep => delTxt.Text = (String.Format("{0}-{1}", ep.EventArgs.ChangeType, ep.EventArgs.FullPath)));


			var fileRename = from ren in
							  Observable.FromEventPattern<RenamedEventHandler, FileSystemEventArgs>(
								  x => _fileSystemWatcher.Renamed += x,
								  x => _fileSystemWatcher.Renamed -= x)
						  where ren.EventArgs.Name.Contains("brad")
						  select ren;
			fileRename.ObserveOn(this).Subscribe(
				ep => renameTxt.Text = (String.Format("{0}-{1}", ep.EventArgs.ChangeType, ep.EventArgs.FullPath)));


			var fileBoth = (from del in fileDel select del)
				.Merge(from ren in fileRename select ren);
			fileBoth.ObserveOn(this).Subscribe(
				ep => bothTxt.Text = (String.Format("{0}-{1}", ep.EventArgs.ChangeType, ep.EventArgs.FullPath)));

		}

        //back to ppt
	}

}